package com.gzyj.web.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gzyj.data.web.cljk.OrgCarTreeDTO;
import com.gzyj.data.web.cljk.PointLatLng;
import com.gzyj.data.web.cljk.VehPositionDataDTO;
import com.gzyj.pojo.anbiao.AnbiaoVehicle;
import com.gzyj.pojo.web.dept.BladeDept;
import com.gzyj.pojo.web.tpvdata.Tpvehdata;
import com.gzyj.web.config.SysConfig;
import com.gzyj.web.mapper.dept.BladeDeptMapper;
import com.gzyj.web.mapper.veh.AnbiaoVehicleMapper;
import com.gzyj.web.service.MapFixService;
import com.gzyj.web.service.WebSocketService;
import com.gzyj.web.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;

@Service
public class RealtimeGPSListener {

    @Autowired
    private WebSocketService webSocketService;

    @Autowired
    private AnbiaoVehicleMapper anbiaoVehicleMapper;

    @Autowired
    private BladeDeptMapper bladeDeptMapper;

    @Autowired
    private MapFixService mapFixService;

    public String getDirectionDescr(String directions) {
        String descr = "";
        int direction = Integer.valueOf(directions);
        if (direction == 0) {
            descr = "正北";
        } else if (direction == 90) {
            descr = "正东";
        } else if (direction == 180) {
            descr = "正南";
        } else if (direction == 270) {
            descr = "正西";
        } else if (direction == 45) {
            descr = "东北";
        } else if (direction == 135) {
            descr = "东南";
        } else if (direction == 225) {
            descr = "西南";
        } else if (direction == 315) {
            descr = "西北";
        } else if (direction < 90) {
            descr = "东偏北" + direction + "度";
        } else if (direction > 90 && direction < 180) {
            descr = "东偏南" + (direction - 90) + "度";
        } else if (direction > 180 && direction < 270) {
            descr = "西偏南" + (270 - direction) + "度";
        } else if (direction > 270 && direction < 360) {
            descr = "西偏北" + (direction - 270) + "度";
        }
        return descr;
    }

    @KafkaListener(topics = "${kafka.queue.realgps}", groupId = "${kafka.queue.realgps}", containerFactory = "kafkaListenerContainerFactory")
    public void onMessage(List<ConsumerRecord<String, String>> records) {
        for (ConsumerRecord<String, String> record : records) {
            Tpvehdata tpvehdata = JSON.parseObject(record.value(), Tpvehdata.class);
            AnbiaoVehicle vehicle = anbiaoVehicleMapper.selectById(tpvehdata.getVehid());

            JSONObject result = new JSONObject();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            {
                /**
                 * 构造树形节点
                 */
                OrgCarTreeDTO treeSelectVn = new OrgCarTreeDTO();
                String parentNodeId = tpvehdata.getDeptId();
                String vehicleId = tpvehdata.getVehid();

                String gpsTime = sdf.format(tpvehdata.getTime());
                int secs = DateUtils.secToNowTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, gpsTime));
                String stopTimes = secs > SysConfig.day7Sec ? ">7天" : secs > SysConfig.daySec ? ">1天" : DateUtils.secToTime(secs);
                boolean online = (0 < secs && secs < SysConfig.onlineTime * SysConfig.minuteSec) ? true : false;
                long velocity = Long.valueOf(String.valueOf(tpvehdata.getVelocity()));
                String nodeDescr = tpvehdata.getVeNumber() + "_" + tpvehdata.getVeColor();
                int alarm = tpvehdata.getAlarm();
                int acc = tpvehdata.getAcc();
                int zhongduanleixing = vehicle.getZhongduanleixing();
                int platformconnectiontype = Integer.valueOf(vehicle.getPlatformconnectiontype());

                int flameout = tpvehdata.getFlameout();

                int stopTime = 0;
                if (StringUtils.isNotEmpty(tpvehdata.getStopTime())) {
                    stopTime = DateUtils.secStrToNowTime(tpvehdata.getStopTime());
                }
                flameout = stopTime <= 0 ? secs : stopTime + secs;
                String flameoutTimes = flameout > SysConfig.day7Sec ? ">7天" : flameout > SysConfig.daySec ? ">1天" : DateUtils.secToTime(flameout);

                if (online) {
                    String sendTime = "" + sdf.format(tpvehdata.getTime());
                    if (velocity > 1) {

                        int secsGps = DateUtils.secToNowTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, sendTime));
                        boolean isRun = (0 < secsGps && secsGps < SysConfig.onlineTime * SysConfig.minuteSec) ? true : false;
                        if (isRun) {
                            // gps时间在半小时内
                            nodeDescr += "_行驶[" + (int) velocity + "km/h]";
                            treeSelectVn.setStatus(SysConfig.iruncar);
                        } else {
                            // gps时间在半小时以前
                            int iflameout = DateUtils.secToNowTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, sendTime));
                            flameoutTimes = iflameout > SysConfig.day7Sec ? ">7天" : iflameout > SysConfig.daySec ? ">1天" : DateUtils.secToTime(iflameout);
                            if (acc == 1) {
                                nodeDescr += "_停车[" + flameoutTimes + "]";
                                treeSelectVn.setStatus(SysConfig.istopcar);
                            } else {
                                nodeDescr += "_熄火[" + flameoutTimes + "]";
                                treeSelectVn.setStatus(SysConfig.iflameoutcar);
                            }
                        }
                    } else {
                        int iflameout = 0;
                        if (DateUtils.secStrToNowTime(sendTime) > stopTime) {
                            // gps时间比停止时间还要远
                            iflameout = DateUtils.secToNowTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, sendTime));
                            flameoutTimes = iflameout > SysConfig.day7Sec ? ">7天" : iflameout > SysConfig.daySec ? ">1天" : DateUtils.secToTime(iflameout);
                        }

                        if (acc == 1) {
                            nodeDescr += "_停车[" + flameoutTimes + "]";
                            treeSelectVn.setStatus(SysConfig.istopcar);
                        } else {
                            nodeDescr += "_熄火[" + flameoutTimes + "]";
                            treeSelectVn.setStatus(SysConfig.iflameoutcar);
                        }
                    }
                } else {
                    if ("".equals(gpsTime) || SysConfig.neverOnlineTime.equals(gpsTime)) {
                        nodeDescr += "_从未上线";
                        treeSelectVn.setStatus(1);
                        treeSelectVn.setStatus(SysConfig.ineverOn);
                    } else {
                        nodeDescr += "_离线[" + stopTimes + "]";
                        treeSelectVn.setStatus(SysConfig.iofflinecar);
                    }
                }
                treeSelectVn.setVideo(zhongduanleixing == 0 ? 1 : 2);
                treeSelectVn.setConnectType(platformconnectiontype);
                treeSelectVn.setAlarm(alarm);
                treeSelectVn.setType(SysConfig.nodeTypeCar);
                treeSelectVn.setId(vehicleId);
                treeSelectVn.setPid(parentNodeId);
                treeSelectVn.setLabel(nodeDescr);
                treeSelectVn.setSimNo(tpvehdata.getDeviceId());
                treeSelectVn.setAcc(tpvehdata.getAcc());
                treeSelectVn.setVehNo(tpvehdata.getVeNumber());
                treeSelectVn.setVehColor(tpvehdata.getVeColor());
                treeSelectVn.setPlatformConnectType(platformconnectiontype);
                treeSelectVn.setAlarmNote(StringUtils.isNotEmpty(tpvehdata.getAlarmNote()) ? tpvehdata.getAlarmNote() : null);

                result.put("treeNode", treeSelectVn);

            }
            {


                BladeDept dept = bladeDeptMapper.selectById(vehicle.getDeptId());
                int onlineTime = SysConfig.onlineTime * SysConfig.minuteSec;

                VehPositionDataDTO positionData = new VehPositionDataDTO();
                positionData.setVehId(tpvehdata.getVehid());
                positionData.setPlateNo(tpvehdata.getVeNumber());
                positionData.setPlateColor(tpvehdata.getVeColor());
                positionData.setCompanyName(dept.getDeptName());
                positionData.setRunType(tpvehdata.getShiyongxingzhi());
                positionData.setTerminalId(tpvehdata.getDeviceId());
                positionData.setSimNum(tpvehdata.getDeviceId());
                positionData.setAcc(tpvehdata.getAcc()==1 ? "开" : "关");
                positionData.setSignalNum(tpvehdata.getWiFiSignal()==null ? "0" : String.valueOf(tpvehdata.getWiFiSignal()));
                positionData.setSatelliteNum(tpvehdata.getSatelliteLen()==null ? "0" : String.valueOf(tpvehdata.getSatelliteLen()));
                String gpsTime = sdf.format(tpvehdata.getTime());
                if ("".equals(gpsTime) || SysConfig.neverOnlineTime.equals(gpsTime)) {
                    positionData.setOnlineType(SysConfig.neverOnlineMsg);
                    positionData.setOnlineTypeNum(0);
                } else {
                    int secs = DateUtils.secToNowTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, gpsTime));
                    positionData.setOnlineType((0 < secs && secs < onlineTime) ? SysConfig.onlineMsg : SysConfig.offLineMsg);
                    positionData.setOnlineTypeNum((0 < secs && secs < onlineTime) ? 1 : 2);
                }
                positionData.setDirectionNum(tpvehdata.getAngle());
                positionData.setAlarmStatus(tpvehdata.getAlarm());
                positionData.setAlarmType(tpvehdata.getAlarmNote());
                positionData.setGpsTime(gpsTime);
                positionData.setSpeed(String.valueOf(tpvehdata.getVelocity()));
                positionData.setDirection(getDirectionDescr(String.valueOf(tpvehdata.getAngle())));
                positionData.setLocalStatus(tpvehdata.getLocate() == 1 ? "定位" : "不定位");
                positionData.setAltitude("");
                positionData.setLat(tpvehdata.getLatitude());
                positionData.setLng(tpvehdata.getLongitude());
                PointLatLng mapPoint = mapFixService.fix(positionData.getLat(), positionData.getLng(), "");
                positionData.setMaplat(mapPoint.getLat());
                positionData.setMaplng(mapPoint.getLng());
                positionData.setDriverName(tpvehdata.getDriverName());

                if (tpvehdata.getOil() != null)
                    positionData.setOil(tpvehdata.getOil());
                else positionData.setOil(0);
                if (tpvehdata.getMileZongduan() != null)
                    positionData.setMileZongduan(tpvehdata.getMileZongduan());
                else positionData.setMileZongduan(0);
                if (tpvehdata.getMileToday() != null)
                    positionData.setMileToday(tpvehdata.getMileToday());
                else positionData.setMileToday(0d);
                if (tpvehdata.getMileTotal() != null)
                    positionData.setMileTotal(tpvehdata.getMileTotal());
                else positionData.setMileTotal(0d);

                String uploadTime = sdf.format(tpvehdata.getSystime());

                int stopTime = DateUtils.secStrToNowTime(tpvehdata.getStopTime());

                int secs = DateUtils.secToNowTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, uploadTime));
                String stopTimes = secs > SysConfig.day7Sec ? ">7天" : secs > SysConfig.daySec ? ">1天" : DateUtils.secToTime(secs);
                boolean online = (0 < secs && secs < SysConfig.onlineTime * SysConfig.minuteSec) ? true : false;

                if (online) {

                    if (Integer.valueOf(positionData.getSpeed()) > 1) {

                        int secsGps = DateUtils.secToNowTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, gpsTime));
                        boolean isRun = (0 < secsGps && secsGps < SysConfig.onlineTime * SysConfig.minuteSec) ? true : false;
                        if (isRun) {
                            // gps时间在半小时内
                            positionData.setStatus(SysConfig.iruncar);
                        } else {
                            // gps时间在半小时以前
                            if (tpvehdata.getAcc() == 1) {
                                positionData.setStatus(SysConfig.istopcar);
                            } else {
                                positionData.setStatus(SysConfig.iflameoutcar);
                            }
                        }
                    } else {


                        if (tpvehdata.getAcc() == 1) {

                            positionData.setStatus(SysConfig.istopcar);
                        } else {

                            positionData.setStatus(SysConfig.iflameoutcar);
                        }
                    }
                } else {
                    if ("".equals(uploadTime) || SysConfig.neverOnlineTime.equals(uploadTime)) {
                        positionData.setStatus(SysConfig.ineverOn);
                    } else {

                        positionData.setStatus(SysConfig.iofflinecar);
                    }
                }

                result.put("mapData",positionData);
            }




            webSocketService.sendMessage(result.toJSONString());


        }
    }

}
